package com.xwyzsn.quartz.task;

import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiRobotSendRequest;
import com.dingtalk.api.response.OapiRobotSendResponse;
import com.taobao.api.ApiException;
import com.xwyzsn.common.core.domain.entity.SysUser;
import com.xwyzsn.system.domain.Borrow;
import com.xwyzsn.system.service.IBorrowService;
import com.xwyzsn.system.service.ISysUserService;
import org.apache.commons.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Component("myTask")

public class MyTask {


    @Autowired
    private IBorrowService borrowService;

    @Autowired
    private ISysUserService sysUserService;

    public void sendToDingTalk(List<String> phoneList ) {
        String CUSTOM_ROBOT_TOKEN = "01d2db2f6e76ba02ed2c785f7fe11a51aa6fa444117df75d8c10526d613a1481";
//        String signData = "SEC60123cbec46484ed33aa8f70e9a089e14ef2240e9ab09b1a4bfc24e99b67c121";
        try {
            DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/robot/send?access_token="+CUSTOM_ROBOT_TOKEN);
            OapiRobotSendRequest request = new OapiRobotSendRequest();
            request.setMsgtype("text");
            OapiRobotSendRequest.At at = new OapiRobotSendRequest.At();
            OapiRobotSendRequest.Text text = new OapiRobotSendRequest.Text();
            text.setContent("TEST : 设备告警通知 \n 您有设备逾期请及时归还\n");
            request.setText(text);
            at.setAtMobiles(phoneList);
            request.setAt(at);
            OapiRobotSendResponse response = client.execute(request);

        } catch (ApiException e) {
            e.printStackTrace();
        }
    }
    public void notice(){
        List<Borrow> out = borrowService.selectAll();
        List<Borrow> overDueList = new ArrayList<>();
        for (Borrow borrow : out) {
            boolean f = (borrow.getEndTime().getTime() < System.currentTimeMillis()) && (Objects.equals(borrow.getStatus(), "未归还"));
            if (f) {
                overDueList.add(borrow);
            }
        }
        List<String> phoneList = new ArrayList<>();
        if (!overDueList.isEmpty()) {
            for(Borrow borrow : overDueList){
                long userId = borrow.getStuId();
                SysUser user = sysUserService.selectUserById(userId);
                String number = user.getPhonenumber();
                phoneList.add(number);
            }
        }
        sendToDingTalk(phoneList);
    }
}
